﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Delegale.Interface;
using MvcApplication2.Models;
using MvcApplication2.Models.Form;
using MvcApplication2.Delegale.Concrete;
using Webdiyer.WebControls.Mvc;
using StructureMap;
namespace MvcApplication2.Controllers
{
    public class CategoryController : Controller
    {
        //
        // GET: /Category/
        ProductDbcontext db = new ProductDbcontext();
        private ICategoryDelegate ICategoryDelegate;

        public CategoryController()
        {
            this.ICategoryDelegate = new CategoryDelegate(new ProductDbcontext());
        }

        public CategoryController(ICategoryDelegate catelogriRepository)
        {
            this.ICategoryDelegate = catelogriRepository;
        }

        public ActionResult Category(int? id)
        {
            CategoryForm form = new CategoryForm();
            PagedList<Category> list = db.Categorys.OrderBy(p =>p.Id).ToPagedList(id ?? 1, 10);//categoryGenerator.GetCategorys().ToPagedList(Pagenumber??1,10);
            form.categoryPagedList = list;
            form.cboCategoryParent = new SelectList(ICategoryDelegate.ListCategory(), "Id", "Name");
            form.PageNumber = id ?? 1;
            return View(form);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SaveCategory (CategoryForm form )
        {
            Category obj = ICategoryDelegate.ConvetToEntityCategory(form);
            obj = ICategoryDelegate.InsertCategory(obj);
            if (obj != null)
                return Redirect("~/Category/Category");
            else
                form.Message = "Quá trình lưu gặp sự cố xin vui lòng thử lại!";
            return View("~/Views/Category/Category.cshtml",form);
        }
        public JsonResult CheckName(string name)
        {
            bool kq = ICategoryDelegate.CheckNameCategory(name);
            return Json(kq, JsonRequestBehavior.AllowGet);
        }
        public JsonResult Delete(int id)
        {
            bool kq = ICategoryDelegate.DeleteCategory(id);
            return Json(kq, JsonRequestBehavior.AllowGet);
        }
        public JsonResult Edit(int id)
        {
            Category obj = ICategoryDelegate.GetCategoryByID(id);
            string[] str = new string[] { obj.Id.ToString(), obj.Name, obj.ParentId != null ? obj.ParentId.Value.ToString() : "0" };
            return Json(str, JsonRequestBehavior.AllowGet);
        }
    }
}
